<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/4/23
 * Time: 下午10:06
 */

namespace App\Busi\Modules\Resource;


use App\Busi\Modules\BaseBusi;
use App\Busi\Traits\CompanyTrait;
use App\Busi\Traits\UserTrait;
use App\Exceptions\ErrorCode\UserError;
use App\Exceptions\UserException;
use App\Http\Requests\CompanyAddRo;
use App\Models\Company;
use App\Models\User;
use App\Util\StringUtil;

class CompanyAddBusi extends BaseBusi
{
    use UserTrait,CompanyTrait;
    public function handle(CompanyAddRo $ro){
        $uid = $ro->uid;
        $name = $ro->name;
        $province_id = $ro->province_id;
        $city_id = $ro->city_id;
        $address = $ro->address;
        $scale = $ro->scale;
        $licence_poster = $ro->licence_poster;
        $img_host = config("admin.upload.host");
        $host_count = strlen($img_host);
        $licence_poster = substr($licence_poster,$host_count,strlen($licence_poster)-$host_count);
        $user = $this->getUserByUid($uid);
        if(!$user){
            throw new UserException(UserError::USER_NOT_EXIST);
        }
        $raw_company = $this->getCompanyByUid($uid);
        if($raw_company){
            //如果公司已认证且审核已通,则不能修改
            if($raw_company['flag'] == 3){
                $data = [
                    "msg"=>"公司已通过认证,不能再修改认证信息"
                ];
                return $data;
            }
            $update = [
                "name"=>$name,
                "province_id"=>$province_id,
                "city_id"=>$city_id,
                "address"=>$address,
                "scale"=>$scale,
                "licence_poster"=>$licence_poster,
            ];
            Company::where("uid",$uid)->update($update);
            $data = [
                "msg" =>"更新成功"
            ];
            return $data;
        }

        $company = new Company();
        $company->uid = $uid;
        $company->name = $name;
        $company->province_id = $province_id;
        $company->city_id = $city_id;
        $company->address =$address;
        $company->scale = $scale;
        $company->licence_poster = $licence_poster;
        $company->account = StringUtil::getAccount();
        $res = $company->save()?1:0;
        $data = [
            "msg" =>"上传成功"
        ];
        return $data;

    }
}